export function formatDate(date, format) {
    const year = date.getFullYear().toString();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');

    return format
        .replace(/yyyy/g, year)
        .replace(/MM/g, month)
        .replace(/dd/g, day)
        .replace(/HH/g, hours)
        .replace(/mm/g, minutes)
        .replace(/ss/g, seconds);
}

export function formatRemainTime(time) {
    let remainTimeStr = ''
    const seconds = Math.floor(time / 1000)
    const days = Math.floor(seconds / (3600 * 24))
    const hours = Math.floor((seconds % (3600 * 24)) / 3600)
    // const minutes = Math.floor((seconds % 3600) / 60)
    // const remainingSeconds = seconds % 60
    if (days > 0) {
        remainTimeStr += `${ days }天`
    }
    if (hours > 0) {
        remainTimeStr += `${ hours }小时`
    }
    return `还剩${ remainTimeStr }自动确认`
}


/**
 * 创建一个滚动动画
 * @param scrollStart 动画开始滚动位置
 * @param scrollEnd 动画结束滚动位置
 * @param valueStart 动画值开始值
 * @param valueEnd 动画值结束值
 */
export function createAnimation(scrollStart, scrollEnd, valueStart, valueEnd) {
    return function (nowScroll) {
        if (nowScroll <= scrollStart) {
            return valueStart
        }
        if (nowScroll >= scrollEnd) {
            return valueEnd
        }
        // (nowScroll - scrollStart) / (scrollEnd - scrollStart) 当前滚动在咕哝的那个起始值中的比例
        // 用value的总值 * 比例 = value的值
        // 由于valueStart可能不是0 ， 所以需要加上valueStart
        return ((valueEnd - valueStart) * (nowScroll - scrollStart) / (scrollEnd - scrollStart)) + valueStart
    }
}

/**
 * 从数组中找到比较项并且删除
 * @param originalList 原数组
 * @param compareItem 比较项目
 * @param field 比较字段
 */
export function compareToDelListItem(originalList, compareItem, field) {
    const delIndex = originalList.findIndex((item) => item[field] === compareItem[field]);
    if (delIndex >= 0) {
        originalList.splice(delIndex, 1);
        return true
    }
    return false
}

/**
 * 过滤File类型
 * @param file
 * @param excludeTypeArr 需要排除的类型
 */
export function filterFileType(file, excludeTypeArr) {
    let suffix, name
    // #ifndef MP-WEIXIN
    name = file.name
    suffix = name.slice(name.lastIndexOf('.') + 1)
    // #endif
    // #ifdef MP-WEIXIN
    name = file.url
    suffix = name.slice(name.lastIndexOf('.') + 1)
    // #endif
    return excludeTypeArr.includes(suffix)
}

/**
 * 阿拉伯数字转换中文数字
 * @param number
 */
export function arabicToChinese(number) {
    const chineseNumberMap = {
        0: '零',
        1: '一',
        2: '二',
        3: '三',
        4: '四',
        5: '五',
        6: '六',
        7: '七',
        8: '八',
        9: '九',
        10: '十'
    };

    const chineseUnitMap = {
        10: '十',
        100: '百',
        1000: '千',
        10000: '万',
        100000: '十万',
        1000000: '百万',
        10000000: '千万',
        100000000: '亿',
        1000000000: '十亿',
        10000000000: '百亿',
        100000000000: '千亿',
        1000000000000: '兆'
    };

    if (number <= 10) {
        return chineseNumberMap[number]
    }

    let chineseNumber = '';
    let num = number;
    for (let unit of [1000000000000, 100000000000, 10000000000, 1000000000, 100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1]) {
        if (num >= unit) {
            let count = Math.floor(num / unit);
            chineseNumber += chineseNumberMap[count] + (chineseUnitMap[unit] ? chineseUnitMap[unit] : '');
            num %= unit; // 取余
        } else if (chineseNumber !== '') {
            chineseNumber += chineseNumberMap[0]; // 添加零，保持位数对齐
        }
    }
    return chineseNumber;
}


export function hasNetWork() {
    return new Promise < boolean > ((resolve, reject) => {
        wx.getNetworkType({
            success(res) {
                console.log(res);
                if (res.networkType === 'none') {
                    resolve(false)
                } else {
                    resolve(true)
                }
            }
        })
    })
}

/**
 * 获取两数之间的随机数
 * @param min
 * @param max
 */
export function getRandom(min, max) {
    return (Math.random() * (max - min) + min).toFixed(2);
}

/**
 * 计算未来时间距离当前时间的时间对象
 * @param futureTime 未来时间的时间戳（毫秒）
 */
export function getTimeAfterNow(futureTime) {
    const nowTime = Date.now()
    const timeDiff = futureTime - nowTime // 时间差
    if (timeDiff <= 0) {
        return {
            days: '00',
            hours: '00',
            minutes: '00',
            seconds: '00'
        }
    }
    let hours = Math.floor((timeDiff) / (1000 * 60 * 60));
    let minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);
    return {
        hours: hours.toString().padStart(2, '0'),
        minutes: minutes.toString().padStart(2, '0'),
        seconds: seconds.toString().padStart(2, '0')
    }
}

/**
 * 生成本周的日历
 * @return {Date[]}
 */
export function generationWeek() {
    const MillisecondsOfTheDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
    let today = new Date();
    let dayOfTheWeek = today.getDay(); // 当前天在本周的位置
    let calendar = []
    let startOfWeek = new Date(today - (dayOfTheWeek * MillisecondsOfTheDay) + MillisecondsOfTheDay); // 本周开始的位置
    for (let i = 0; i < 7; i++) {
        let day = new Date(startOfWeek.getTime() + i * MillisecondsOfTheDay);
        calendar.push(day)
    }
    return calendar
}


/**
 * @description: 对象转query串
 * @param {*} obj
 * @param {*} noFilterEmpty 默认false 去除空值再拼接字符串
 * @return {*}
 */
export const getQueryString = (obj, noFilterEmpty = false) => {
    if (!obj) return '';

    let newObj = {...obj};
    if (!noFilterEmpty) {
        newObj = filterParams(newObj)
    }
    return new URLSearchParams(Object.entries(newObj)).toString()
}

/**
 * @description: query串转对象
 * 支持小程序
 * @param query
 */
export const getUrlQuery = (query) => {
    if (!query) return
    if (query.indexOf("?") > 0) {
        query = query.split("?").at(-1) // 选取?后面的
    }
    const queryList = query.split("&").map(item => item.split("="))
    const entries = new Map(queryList);
    return Object.fromEntries(entries);
}

/**
 * @description: 去除对象中的空值
 * @param {*} obj
 * @return {*}
 */
export const filterParams = (obj) => {
    let newObj = {};
    for (const key in obj) {
        //如果对象属性的值不为空，就保存该属性（如果属性的值为0 false，保存该属性。如果属性的值全部是空格，属于为空。）
        if ((obj[key] === 0 || obj[key] === false || obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
            newObj[key] = obj[key];
        }
    }
    return newObj;
}

export const checkPhone = (phone) => {
    return /^1[3456789]\d{9}$/.test(phone)
}
